package com.charlotte.study.gupao.observer.mouse.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author junjie.ding
 * @date 2020/3/24
 */
public class EventContext {

    private Map<String, Event> eventMap = new HashMap<>();

    public void addListener(String eventType, EventListener target, Method callback){
        eventMap.put(eventType, new Event(target, callback));
    }

    public void addListener(String eventType, EventListener target){
        try {
            this.addListener(eventType, target, target.getClass().getMethod("on" + toLowerFirstCase(eventType), Event.class));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    protected void trigger(String trigger){
        if(!this.eventMap.containsKey(trigger)){
            return;
        }
        trigger(this.eventMap.get(trigger).setTrigger(trigger));
    }

    private String toLowerFirstCase(String eventType){
        char[] chars = eventType.toCharArray();
        chars[0] -=32;
        return new String(chars);
    }

    private void trigger(Event event){
        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        try {
            event.getCallback().invoke(event.getTarget(),event);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
